import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/XImage/ImageWidget.dart';
import 'package:orginone/config/theme/UIConfig.dart';
import 'package:orginone/components/ChatSessionWidget/components/MessageListWidget/components/DetailItemWidget/DetailItemWidget.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/regex/regex_utils.dart';
import 'package:orginone/dart/core/work/rules/lib/tools.dart';
import 'package:orginone/main.dart';
import 'package:orginone/utils/file_utils.dart';
import 'package:orginone/utils/string_util.dart';
import 'package:orginone/config/theme/unified_style.dart';
import '../../../../../../../../dart/core/chat/activity.dart';
import '../../../../../../../../dart/core/chat/session.dart';
import '../../../../../../../../dart/core/provider/session.dart';
import '../../../../../../../../routers/pages.dart';
import '../../../../../../../../routers/router_const.dart';
import '../../../../../../../ActivityWidget/ActivityMessageFromChatWidget/ActivityMessageFromChatWidget.dart';
import 'BaseDetailWidget.dart';

///动态详情
class GroupDynamicsDetailWidget extends BaseDetailWidget {
  late final ActivityType msgBody;

  GroupDynamicsDetailWidget({
    super.key,
    required super.isSelf,
    required super.message,
    super.clipBehavior = Clip.hardEdge,
    super.padding = const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
    super.bgColor,
    super.constraints,
    super.isReply = false,
    super.chat,
  }) {
    msgBody = ActivityType.fromJson(jsonDecode(message.msgBody));
  }

  @override
  Widget body(BuildContext context) {
    dynamic entity = null != relationCtrl.user
        ? relationCtrl.user!.findMetadata(msgBody.createUser!)
        : null;

    BoxConstraints boxConstraints =
        BoxConstraints(minWidth: 280.w, maxWidth: UIConfig.screenWidth - 110);
    Widget child = GestureDetector(
      onTap: () {
        onTap(context);
      },
      child: Container(
          constraints: boxConstraints,
          color: Colors.transparent,
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            SizedBox(
              height: 70,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                      child: Container(
                    padding: const EdgeInsets.only(right: 8.0,),
                    child: Text(
                      msgBody.content.trim().isEmpty
                          ? "我发布了一条动态"
                          : StringUtil.breakWord(msgBody.content
                              .replaceAll(RegExp(r'<[^>]*>|&[^;]+;'), '')),
                      style: XFonts.size22Black0,
                      maxLines: 3,
                    ),
                  )),
                  if (msgBody.resource.isNotEmpty)
                    Stack(
                      alignment: Alignment.center,
                      children: [
                        ImageWidget(
                          fit: BoxFit.cover,
                          msgBody.resource[0].poster != null &&
                                  msgBody.resource[0].poster!.isNotEmpty
                              ? shareOpenLink(msgBody.resource[0].poster)
                              : msgBody.resource[0].thumbnailUint8List,
                          radius: 8,
                          size: 60,
                        ),
                        if (FileUtils.isVideo(
                            msgBody.resource[0].extension ?? ""))
                          Positioned(
                            child:
                                XImage.localImage(XImage.videoPlay, width: 20),
                          )
                      ],
                    )
                ],
              ),
            ),
            Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(top: 10.h, bottom: 12.h),
                // child: RegexUtils.isURL(msgBody.linkInfo)
                //     ? renderLinkPreview()
                //     : Container()
            ),
            const Divider(),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    // TeamAvatar(
                    //   info: TeamTypeInfo(userId: msgBody.createUser!),
                    //   size: 22.w,
                    //   circular: true,
                    // ),
                    XImage.entityIcon(entity,
                        size: Size(22.w, 22.w), radius: 5.w),
                    Padding(
                      padding: const EdgeInsets.only(left: 4.0),
                      child: Text(
                        "${entity?.name}",
                        style: XFonts.size18Black3,
                      ),
                    ),
                  ],
                ),
                Text(
                  showChatTime(msgBody.createTime!),
                  style: XFonts.size18Black3,
                  textAlign: TextAlign.end,
                ),
                // Row(
                //   mainAxisAlignment: MainAxisAlignment.spaceAround,
                //   children: [
                //     Row(
                //       children: [
                //         XImage.localImage(XImage.likeOutline, width: 20.w),
                //         Container(
                //             padding: EdgeInsets.only(left: 6.w),
                //             child: Text(
                //               "${msgBody.likes.isEmpty ? '点赞' : msgBody.likes.length}",
                //               style: XFonts.size18Black3,
                //             ))
                //       ],
                //     ),
                //     const SizedBox(width: 8),
                //     Row(
                //       children: [
                //         XImage.localImage(XImage.commentOutline, width: 20.w),
                //         Container(
                //             padding: EdgeInsets.only(left: 6.w),
                //             child: Text(
                //               "${msgBody.comments.isEmpty ? '评论' : msgBody.comments.length}",
                //               style: XFonts.size18Black3,
                //             ))
                //       ],
                //     ),
                //   ],
                // )
              ],
            ),
          ])),
    );
    return child;
  }

  Widget renderLinkPreview() {
    return Container(
        decoration: BoxDecoration(
          color: Colors.grey.withOpacity(0.1),
          borderRadius: const BorderRadius.all(Radius.circular(10)),
        ),
        padding: const EdgeInsets.all(12),
        child: PreViewUrl(
          url: msgBody.linkInfo,
          width: UIConfig.screenWidth - 32,
        ));
  }

  @override
  void onTap(BuildContext context) async {
    //跳转动态详情
    // Navigator.push(context, MaterialPageRoute(builder: (context) {
    //   return ActivityMessageFromChatWidget(
    //     metadata: msgBody,
    //   );
    // }));
    List<ISession> chatsAll = [];
    if (relationCtrl.user?.chats != null) {
      chatsAll.addAll(relationCtrl.user!.chats);
    }
    IChatProvider? chatProvider = relationCtrl.provider.chatProvider;
    if (chatProvider?.chats != null) {
      chatsAll.addAll(chatProvider!.chats);
    }
    ISession? iss = chatsAll.firstWhereOrNull((element) => element.id == msgBody.shareId);
    if (iss != null) {
      RoutePages.to(
          context: context,
          path: Routers.targetActivity,
          data: iss.activity);
    } else {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return ActivityMessageFromChatWidget(
          metadata: msgBody,
        );
      }));
    }
    // ISession? sessionUser = relationCtrl.user?.findMemberChat(msgBody.updateUser!);
    // IActivity iActivity = Activity(sessionUser!.metadata, sessionUser);
    // RoutePages.jumpActivityInfo(iActivity);
    // ActivityMessage imsg = ActivityMessage(msgBody, iActivity);
    // Navigator.push(context, MaterialPageRoute(builder: (context) {
    //   return ActivityMessageOne(item: imsg);
    // }));
  }

  @override
  Widget imageWidget(url) {
    // TODO: implement imageWidget
    throw UnimplementedError();
  }
}
